<template>
  <div class="reader-management">
    <div class="header">
      <h1>读者管理</h1>
      <button class="btn btn-primary" @click="openReaderForm(null)">添加读者</button>
    </div>

    <div class="card">
      <div class="search-bar">
        <input type="text" v-model="readerSearch" placeholder="搜索读者..." style="flex:1">
        <button class="btn btn-primary" @click="searchReaders">搜索</button>
      </div>

      <div class="table-container">
        <table>
          <thead>
          <tr>
            <th>读者ID</th>
            <th>姓名</th>
            <th>性别</th>
            <th>电话</th>
            <th>邮箱</th>
            <th>注册日期</th>
            <th>操作</th>
          </tr>
          </thead>
          <tbody>
          <tr v-for="reader in filteredReaders" :key="reader.id">
            <td>{{ reader.reader_id }}</td>
            <td>{{ reader.name }}</td>
            <td>{{ reader.gender }}</td>
            <td>{{ reader.phone }}</td>
            <td>{{ reader.email }}</td>
            <td>{{ formatDate(reader.register_date) }}</td>
            <td class="action-buttons">
              <button class="btn btn-success" @click="openReaderForm(reader)">编辑</button>
              <button class="btn btn-danger" @click="deleteReader(reader.id)">删除</button>
            </td>
          </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 读者表单弹窗 -->
    <div v-if="showReaderForm" class="modal">
      <div class="modal-content">
        <span class="close" @click="showReaderForm = false">&times;</span>
        <h2>{{ currentReader.id ? '编辑读者' : '添加读者' }}</h2>
        <div class="form-group">
          <label>读者ID</label>
          <input type="text" v-model="currentReader.reader_id">
        </div>

        <div class="form-group">
          <label>姓名</label>
          <input type="text" v-model="currentReader.name">
        </div>

        <div class="form-group">
          <label>性别</label>
          <select v-model="currentReader.gender">
            <option value="男">男</option>
            <option value="女">女</option>
            <option value="其他">其他</option>
          </select>
        </div>

        <div class="form-group">
          <label>电话</label>
          <input type="text" v-model="currentReader.phone">
        </div>

        <div class="form-group">
          <label>邮箱</label>
          <input type="email" v-model="currentReader.email">
        </div>

        <div class="form-group">
          <label>注册日期</label>
          <input type="date" v-model="currentReader.register_date">
        </div>

        <button class="btn btn-primary" @click="saveReader">保存</button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import ReaderService from '@/services/reader'

export default {
  setup() {
    const readers = ref([])
    const readerSearch = ref('')
    const showReaderForm = ref(false)
    const currentReader = ref({
      id: null,
      reader_id: '',
      name: '',
      gender: '男',
      phone: '',
      email: '',
      register_date: new Date().toISOString().split('T')[0]
    })

    const loadReaders = async () => {
      try {
        // 模拟数据
        readers.value = [
          {id: 1, reader_id: 'R2023001', name: '张三', gender: '男', phone: '13800138000', email: 'zhangsan@example.com', register_date: '2023-01-15'},
          {id: 2, reader_id: 'R2023002', name: '李四', gender: '女', phone: '13900139000', email: 'lisi@example.com', register_date: '2023-02-20'},
          {id: 3, reader_id: 'R2023003', name: '王五', gender: '男', phone: '13700137000', email: 'wangwu@example.com', register_date: '2023-03-10'}
        ]
      } catch (error) {
        console.error('获取读者列表失败:', error)
      }
    }

    onMounted(loadReaders)

    const filteredReaders = computed(() => {
      if (!readerSearch.value) return readers.value

      const searchTerm = readerSearch.value.toLowerCase()
      return readers.value.filter(reader =>
          reader.name.toLowerCase().includes(searchTerm) ||
          reader.reader_id.toLowerCase().includes(searchTerm) ||
          (reader.phone && reader.phone.includes(searchTerm)) ||
          (reader.email && reader.email.toLowerCase().includes(searchTerm)))
    })

    const openReaderForm = (reader) => {
      if (reader) {
        currentReader.value = { ...reader }
      } else {
        currentReader.value = {
          id: null,
          reader_id: '',
          name: '',
          gender: '男',
          phone: '',
          email: '',
          register_date: new Date().toISOString().split('T')[0]
        }
      }
      showReaderForm.value = true
    }

    const saveReader = async () => {
      try {
        if (currentReader.value.id) {
          // 更新读者
          await ReaderService.updateReader(currentReader.value)
        } else {
          // 添加读者
          await ReaderService.addReader(currentReader.value)
        }
        showReaderForm.value = false
        loadReaders()
      } catch (error) {
        console.error('保存读者失败:', error)
      }
    }

    const deleteReader = async (id) => {
      if (confirm('确定要删除这位读者吗？')) {
        try {
          await ReaderService.deleteReader(id)
          loadReaders()
        } catch (error) {
          console.error('删除读者失败:', error)
        }
      }
    }

    const searchReaders = () => {
      // 搜索逻辑已在计算属性中实现
    }

    const formatDate = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
    }

    return {
      readers,
      readerSearch,
      filteredReaders,
      showReaderForm,
      currentReader,
      openReaderForm,
      saveReader,
      deleteReader,
      searchReaders,
      formatDate
    }
  }
}
</script>

<style scoped>
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}
</style>